
/******************************************************************************
*@file  : app.c
*@brief : application
******************************************************************************/

#include "app.h" 

IWDT_HandleTypeDef IWDT_Handle;


/******************************************************************************
*@brief : APP_Test
*@param : none
*@return: none
******************************************************************************/
void APP_Test(void)
{
    RCC_OscInitTypeDef      RCC_OscInitStruct = {0};
    
    HAL_PMU_Init();

    HAL_Delay(2000);
    
	/* Enable: RC32K */
    RCC_OscInitStruct.OscType = RCC_OSCTYPE_RC32K;
    RCC_OscInitStruct.RC32K = ENABLE;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        while (1);
    }  
	
	/* Enable: IWDT reset causes system reset */
	__HAL_RCC_IWDT_RESET_ENABLE();
    
    __HAL_RCC_EXTI_CLK_ENABLE();
    
    
    /* Configure IWDT */
    IWDT_Handle.Instance = IWDT;
    IWDT_Handle.Init.Prescaler  = IWDT_CLOCK_PRESCALER_64;
    IWDT_Handle.Init.Reload     = 4000;
    IWDT_Handle.Init.Window     = 4000;//when Window < Reload,The window function will be turned on
    IWDT_Handle.Init.Wakeup     = 2000;//when Wakeup < Reload,The wake-up function will work
    IWDT_Handle.Init.WakeupMode = IWDT_WAKEUP_MODE_IT;
    
    HAL_IWDT_Init(&IWDT_Handle);
    
    HAL_EXTI_SetConfigLine(NULL, IWDT_EXTI_LINE, EXTI_MODE_IT_RISING);

    /* Enable IWDT interrupt */
	NVIC_ClearPendingIRQ(IWDT_WAKEUP_IRQn);
	NVIC_SetPriority(IWDT_WAKEUP_IRQn, 5);
	NVIC_EnableIRQ(IWDT_WAKEUP_IRQn);
    
    HAL_IWDT_Refresh(&IWDT_Handle);
    
    while(1)
    {
        printfS("MCU Enter STOP !\r\n"); 
        
        HAL_EXTI_ClearAllPending();
        
        SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;     // disable systick  
        SCB->ICSR = BIT25;   // clear systick pending bit 
        __set_PRIMASK(1);    // disable interrupt  
        
        HAL_PMU_EnterStop(WAIT_FOR_INT);
        
        __set_PRIMASK(0);    // enable interrupt 
        SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;  // enable systick 
        
        printfS("MCU Exti STOP \r\n");
        
        HAL_IWDT_Refresh(&IWDT_Handle);
        
        HAL_Delay(2000);
        
        HAL_IWDT_Refresh(&IWDT_Handle);
    }
}

void HAL_IWDT_Callback(IWDT_HandleTypeDef *hiwdt)
{
    /* Enter interrupt after reaching wake-up value */
    if(EXTI->PDR == IWDT_EXTI_LINE)
    {
        HAL_IWDT_Refresh(&IWDT_Handle);
        printfS("EXTI->PDR = 0x%08x\r\n", EXTI->PDR);
        EXTI->PDR = IWDT_EXTI_LINE;
        printfS("feed iwdt time = %d\r\n", HAL_GetTick());
    }
}


